package com.wanji.sdk.impl.http;

import cn.hutool.json.JSONUtil;
import com.wanji.protocol.api.DeviceMessage;
import com.wanji.protocol.api.DeviceMessageDecoder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;

import java.nio.charset.StandardCharsets;

public class HttpMessageDecoder extends DeviceMessageDecoder<FullHttpRequest> {

    @Override
    protected DeviceMessage toDeviceMessage(ChannelHandlerContext ctx, FullHttpRequest in) {
        return parseJsonContent(in);
    }


    private DeviceMessage parseJsonContent(FullHttpRequest request) {
        String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType == null || !contentType.contains("application/json")) {
            return null;
        }

        ByteBuf content = request.content();
        if (content.readableBytes() == 0) {
            return null;
        }

        String jsonStr = content.toString(StandardCharsets.UTF_8);
        return JSONUtil.toBean(jsonStr, DeviceMessage.class);
    }
}
